package com.zzyl.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.service.WeChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
@Slf4j
public class WeChatServiceImpl implements WeChatService {
    //获取openid  url
    private static final String GET_OPENID_URL="https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code";
    //获取手机号 url
    private static final String GET_PHONE_URL="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
   //获取accessToken url
    private static final String GET_ACCESS_TOKEN_URL="https://api.weixin.qq.com/cgi-bin/token";

    @Value("${zzyl.framework.wechat.appid}")
    private String appid;
    @Value("${zzyl.framework.wechat.secret}")
    private String secret;
    @Override
    public String getOpenId(String code) {
        //
        Map<String, Object> map=new HashMap<>();
        map.put("appid",appid);
        map.put("secret",secret);
        map.put("js_code",code);
        String jsonStr = HttpUtil.get(GET_OPENID_URL, map);
        JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
        if (jsonObject.getInt("errcode")!=null){
            throw  new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return  jsonObject.getStr("openid");
    }

    @Override
    public String getPhone(String detailCode) {
        //1.声明url
        String accessToken=getAccessToken();
        String url=GET_PHONE_URL+accessToken;
        //2.封装参数
        Map<String ,Object> param=new HashMap<>();
        param.put("code",detailCode);
        //3.发起请求
        String jsonStr = HttpUtil.post(url, JSONUtil.toJsonStr(param));
        log.info("getPhone 返回:{}",jsonStr);
        //4.解析响应
        JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
        if (jsonObject.getInt("errcode")!=0){
            throw  new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
    }

    private String getAccessToken() {
        //1.声明url
        //2.封装参数
        Map<String,Object> param=new HashMap<>();
        param.put("grant_type","client_credential");
        param.put("appid",appid);
        param.put("secret",secret);
        //3.发起请求
        String jsonStr = HttpUtil.get(GET_ACCESS_TOKEN_URL, param);
        log.info("jsonStr:{}",jsonStr);
        //4.解析响应
        JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
        if (jsonObject.getInt("errcode")!=null){
            throw  new RuntimeException(jsonObject.getStr("errmsg"));
        }
        return jsonObject.getStr("access_token");
    }
}
